package com.zjitc.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.zjitc.reggie.common.BaseContext;
import com.zjitc.reggie.entity.Employee;
import com.zjitc.reggie.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取url
        String requestURI = request.getRequestURI();
        log.info("拦截请求" + requestURI);
        //不需要处理的路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/*",
                "/user/sendMsg",
                "/user/login"
        };

        //判断是否要处理路径
        if (check(urls, requestURI)) {
            log.info("不需要处理");
            filterChain.doFilter(request, response);
            return;
        }
        // 判断是否登录
        if (request.getSession().getAttribute("employee") != null) {
            log.info("用户已登录");
            Long id = ((Employee) request.getSession().getAttribute("employee")).getId();

            BaseContext.setCurrentId(id);
            filterChain.doFilter(request, response);
            return;
        }

        if (request.getSession().getAttribute("user") != null) {
            Long user = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(user);
            filterChain.doFilter(request, response);
            return;
        }
        log.info("不能进入路径");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    //路径匹配
    private boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            if (PATH_MATCHER.match(url, requestURI))
                return true;
        }
        return false;
    }
}
